<!--
 * @FileDescription TTS
 * @Author 杨宇翔
 * @Date 20220729 13:41:24
 * @LastEditors 杨宇翔
 * @LastEditTime 20220729 13:41:24
-->
<template>
    <audio ref="audio" controls @canplay="OnCanPlayAsync" @ended="endPlay">
        <slot></slot>
    </audio>
</template>

<script setup lang="ts">
import HomeContent from '@components/Apps/Simulation/HomeContent';
import AudioComponent from '@runtime/module/TTS/AudioComponent';
import TTSComponent from '@runtime/module/TTS/TTSComponent';
import { onBeforeUnmount, onMounted, reactive, ref, Ref, toRef, toRefs, watch } from 'vue';

interface Props {
    stats: { pausable: boolean };
}

const audio: Ref<HTMLAudioElement | null> = ref(null);

const props = defineProps<Props>();
const { stats } = reactive(toRefs(props));

const wantsToPlaying = ref(false);
defineExpose({
    replay,
});
watch(stats, async () => {
    if (audio.value == undefined) {
        return;
    }

    if (stats.pausable) {
        wantsToPlaying.value = false;
        audio.value.pause();
    } else {
        wantsToPlaying.value = true;
        await audio.value.play();
        if (!wantsToPlaying.value) {
            audio.value.pause();
        }
    }
});

async function OnContentChangedAsync(): Promise<void> {
    if (audio.value!.innerHTML == '') {
        audio.value!.pause();
        return
    }

    audio.value!.src = await TTSComponent.Default.ParseAsync(audio.value!.innerHTML);
}

async function OnCanPlayAsync(): Promise<void> {
    if (stats.pausable) {
        audio.value?.pause();
    } else {
        await audio.value?.play();
        if (!wantsToPlaying.value) {
            audio.value?.pause();
        }
    }
}
function endPlay() {
    HomeContent.Default.endplay.value.ended = audio.value?.ended
}
function replay() {
    audio.value?.load()
}
watch(AudioComponent.Default.Volume, (volumn) => {
    if (audio.value == undefined) {
        return;
    }
    audio.value.volume = volumn
});

onMounted(async () => {
    audio.value!.addEventListener('DOMSubtreeModified', OnContentChangedAsync);
    audio.value!.src = await TTSComponent.Default.ParseAsync(audio.value!.innerHTML);
});

onBeforeUnmount(() => {
    audio.value?.pause();
    audio.value!.src = '';
});
</script>

<style scoped></style>